<?php
namespace app\model;

use support\Model;
use app\helper\JwtHelper;
use app\model\Device;

class User extends Model
{
    protected $table = 'users';
    
    protected $fillable = [
        'phone',
        'password',
        'username',
        'nickname',
        'status',
        'openid',
    ];

    protected $hidden = [
        'password',
    ];

    public static function findByPhone($phone)
    {
        return static::where('phone', $phone)->first();
    }

    public static function findByOpenid($openid)
    {
        return static::where('openid', $openid)->first();
    }

    public function generateToken()
    {
        $payload = [
            'id' => $this->id,
            'phone' => $this->phone,
            'iat' => time(),
            'exp' => time() + 24*3600*7 // Token expires in 2 hours
        ];
        
        return JwtHelper::encode($payload);
    }

    public function devices(){
        return $this->belongsToMany(Device::class);
    }
} 